package com.useeinfo.oa.open.admin.maintaining;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.inspection.entity.InspectionOrder;
import com.useeinfo.oa.modules.inspection.entity.PlannerInspection;
import com.useeinfo.oa.modules.inspection.enums.InsOrderOperationEnum;
import com.useeinfo.oa.modules.maintaining.biz.*;
import com.useeinfo.oa.modules.maintaining.entity.FacilityMaintain;
import com.useeinfo.oa.modules.maintaining.entity.PlanExecuteTime;
import com.useeinfo.oa.modules.maintaining.entity.PlannerOrder;
import com.useeinfo.oa.modules.maintaining.entity.PlannerOrderLog;
import com.useeinfo.oa.modules.maintaining.enums.ApplyTypeEnum;
import com.useeinfo.oa.modules.maintaining.enums.OrderOperationEnum;
import com.useeinfo.oa.modules.maintaining.enums.PlannerStatusEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 */
@Controller
@RequestMapping("/web/admin/plannerOrder")
public class PlannerOrderAdminAction {

    @Autowired
    private PlannerOrderBiz plannerOrderBiz;

    @Autowired
    private OrganizationBiz organizationBiz;

    @Autowired
    private DictInfoBiz dictInfoBiz;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private EnterpriseBiz enterpriseBiz;

    @Autowired
    private FacilityBiz facilityBiz;

    @Autowired
    private SystemUserBiz systemUserBiz;

    @Autowired
    private PlannerOrderLogBiz plannerOrderLogBiz;
    @Autowired
    private AuditFlowBiz auditFlowBiz;

    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private FacilityMaintainBiz facilityMaintainBiz;
    @Autowired
    private MaintainTechnologyBiz maintainTechnologyBiz;
    @Autowired
    private MaintainOrderBiz maintainOrderBiz;
    @Autowired
    private PlanExecuteTimeBiz planExecuteTimeBiz;

    /**
     * 打开列表页面
     */
    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/plannerOrder/list");
        return modelAndView;
    }


    /**
     * 查询列表
     *
     * @param pageNowParam
     * @param pageSizeParam
     * @param orderBy
     * @return
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "name", required = false) String name,
                               @RequestParam(value = "required", required = false) String required,
                               @RequestParam(value = "start", required = false) String start,
                               @RequestParam(value = "end", required = false) String end,
                               @RequestParam(value = "period", required = false) String period,


                               @RequestParam(value = "orderBy", required = false) String orderBy, HttpServletRequest request
    ) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("name", name);
        queryParam.getSqlMap().put("required", required);
        queryParam.getSqlMap().put("start", start);
        queryParam.getSqlMap().put("end", end);
        queryParam.getSqlMap().put("period", period);
        if (StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        return plannerOrderBiz.findJSONList(queryParam);
    }

    @RequestMapping("/facilityMaintainJson")
    @ResponseBody
    public JSONObject facilityMaintainJson(String plannerId, String serial
    ) {
        QueryParam queryParam = new QueryParam("-1", "-1");
        if (StringUtils.isNotEmpty(plannerId)) {
            queryParam.getSqlMap().put("plannerId", plannerId);
        }
        if (StringUtils.isNotEmpty(serial)) {
            queryParam.getSqlMap().put("serial", serial);
        }
        return facilityMaintainBiz.findJQJSONList(queryParam);
    }


    /**
     * 获取编辑页面
     */
    @RequestMapping("/editPage")
    public ModelAndView getEditPage(@RequestParam(value = "id", required = false) String id) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        ModelAndView modelAndView = new ModelAndView();
        if (sessionEnterprise != null) {
            modelAndView.addObject("enterprise", sessionEnterprise);
        }
        PlannerOrder plannerOrder;
        if (StringUtils.isNotEmpty(id)) {
            plannerOrder = plannerOrderBiz.findModel(StringConverters.null2Long(id));
        } else {
            plannerOrder = new PlannerOrder();
            plannerOrder.setSerial(StringConverters.getRandomString(10));
        }
        String filePath = "";
        String fileName = "";
        if (plannerOrder != null && plannerOrder.getResource() != null) {
            Resource resource = plannerOrder.getResource();
            filePath = Configuration.getConfigurationByName("hostUrl") + "/" + resource.getPath();
            fileName = resource.getResourceName();
        }
        modelAndView.addObject("plannerOrder", plannerOrder);
        modelAndView.addObject("fileName", fileName);
        modelAndView.addObject("filePath", filePath);

        modelAndView.setViewName("pages/admin/plannerOrder/edit");
        return modelAndView;
    }

    /**
     * 获取编辑页面，复制新增
     */
    @RequestMapping("/copyEditPage")
    public ModelAndView copyEditPage(@RequestParam(value = "id", required = false) String id) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        ModelAndView modelAndView = new ModelAndView();
        if (sessionEnterprise != null) {
            modelAndView.addObject("enterprise", sessionEnterprise);
        }
        PlannerOrder plannerOrder = plannerOrderBiz.findModel(StringConverters.null2Long(id));
        PlannerOrder plannerOrder1=new PlannerOrder();
        BeanUtils.copyProperties(plannerOrder, plannerOrder1);
        String serial = StringConverters.getRandomString(10);
        plannerOrder1.setSerial(serial);
        String filePath = "";
        String fileName = "";
        if (plannerOrder != null && plannerOrder.getResource() != null) {
            Resource resource = plannerOrder.getResource();
            filePath = Configuration.getConfigurationByName("hostUrl") + "/" + resource.getPath();
            fileName = resource.getResourceName();
        }
        Set<FacilityMaintain> facilityMaintainSet = plannerOrder.getFacilityMaintains();
        Set<FacilityMaintain> facilityMaintains = new HashSet<>();
        facilityMaintainSet.forEach(x -> {
            facilityMaintainBiz.saveCopy(x, serial);
        });

        plannerOrder1.setId(null);
        plannerOrder1.setFacilityMaintains(facilityMaintains);
        modelAndView.addObject("plannerOrder", plannerOrder1);
        modelAndView.addObject("fileName", fileName);
        modelAndView.addObject("filePath", filePath);

        modelAndView.setViewName("pages/admin/plannerOrder/edit");
        return modelAndView;
    }

    /**
     * 复制新增 点击功能 前进行时间判断
     * @param id 计划单id
     * @return ResultDto
     */
    @ResponseBody
    @RequestMapping("/beforcopyEditPageCheck")
    public ResultDto beforcopyEditPageCheck(@RequestParam(value = "id") String id) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 工单计划表
        PlannerOrder plannerOrder = plannerOrderBiz.findModel(StringConverters.null2Long(id));
        // 判断计划表中的开始时间是不是在当前时间之后，如果是在当前时间之前报错
        Date startTime = plannerOrder.getStartTime();
        Date nowtime = formatter.parse(formatter.format(new Date()));
        if (startTime.compareTo(nowtime) == -1) {
            return ResultUtil.error("复制计划时间必须大于当前时间");
        }
        return ResultUtil.success("OK");
    }





    /**
     * 详情页面
     *
     * @param plannerOrderId
     * @return
     */
    @RequestMapping("/detail")
    public ModelAndView getDetail(String plannerOrderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/plannerOrder/detail");
        return modelAndView;
    }

    /**
     * 保存操作
     *
     * @param plannerOrder
     * @return
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(PlannerOrder plannerOrder,
                                 String facilityMaintainIds, HttpServletRequest request,
                                 @RequestParam(value = "pic1", required = false) MultipartFile pic1,
                                 @RequestParam(value = "sImg1", required = false) String sImg1,
                                 @RequestParam(value = "start", required = false) String start,
                                 @RequestParam(value = "end", required = false) String end,
                                 @RequestParam(value = "resourceId", required = false) String resourceId,
                                 @RequestParam(value = "selectCompleteAuditFlowId[]", required = false) List<String> selectCompleteAuditFlowIds,
                                 @RequestParam(value = "selectDelayAuditFlowId[]", required = false) List<String> selectDelayAuditFlowIds,
                                 @RequestParam(value = "selectCancelAuditFlowId[]", required = false) List<String> selectCancelAuditFlowId,
                                 @RequestParam(value = "selectOrganizationId[]", required = false) List<String> selectOrganizationIds,
                                 @RequestParam(value = "selectPeriodInstallId[]", required = false) List<String> selectPeriodInstallIds
    ) {
        return plannerOrderBiz.save(plannerOrder, pic1, sImg1, start, end, selectCompleteAuditFlowIds, selectDelayAuditFlowIds, selectCancelAuditFlowId,
                selectOrganizationIds, selectPeriodInstallIds, request, facilityMaintainIds,resourceId);
    }

    /**
     * 删除计划工单
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id,HttpServletRequest request) {
        PlannerOrder plannerOrder = plannerOrderBiz.findModel(StringConverters.null2Long(id));
        plannerOrderBiz.deleteLogic(plannerOrderBiz.findModel(StringConverters.null2Long(id)));
        //添加日志
        plannerOrderLogBiz.savePlannerLog(plannerOrder, OrderOperationEnum.DELETE,request);
        //删除时间记录
        planExecuteTimeBiz.deleteTime(StringConverters.null2Long(id));
        return ResultUtil.success();
    }

    /**
     * 指定接单人列表跳转页
     *
     * @param plannerOrderId
     * @return
     */
    @RequestMapping("/assignUser")
    public ModelAndView assignUser(String plannerOrderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("plannerId", plannerOrderId);
        modelAndView.setViewName("pages/admin/plannerOrder/assignUser");
        return modelAndView;
    }

    /**
     * 指定岗位列表跳转页
     *
     * @param plannerOrderId
     * @return
     */
    @RequestMapping("/assignPosition")
    public ModelAndView assignPosition(String plannerOrderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("plannerId", plannerOrderId);
        modelAndView.setViewName("pages/admin/plannerOrder/assignPosition");
        return modelAndView;
    }

    //指定人员json数据
    @RequestMapping("/getUserByArea")
    @ResponseBody
    public JSONObject getUserByArea(String plannerId, HttpServletRequest request,
                                    @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                    @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        PlannerOrder plannerOrder = plannerOrderBiz.findModel(StringConverters.null2Long(plannerId));
        String authorityName = Configuration.getConfigurationByName("maintainAuthorityName");
        return systemUserBiz.getSystemUserJson(null, plannerOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam,plannerOrder.getEnterprise());
    }

    //指定岗位json数据
    @RequestMapping("/getPositionByArea")
    @ResponseBody
    public JSONObject getPositionByArea(String plannerId, HttpServletRequest request,
                                        @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                        @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        PlannerOrder plannerOrder = plannerOrderBiz.findModel(StringConverters.null2Long(plannerId));
        String authorityName = Configuration.getConfigurationByName("maintainAuthorityName");
        return positionBiz.getPositionJson(null, plannerOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam);
    }


    /**
     * 保存指定人
     *
     * @param assignIds
     * @param plannerId
     * @return
     */
    @RequestMapping("/saveAssignList")
    @ResponseBody
    public ResultDto saveAssignList(String assignIds, String plannerId, HttpServletRequest request) {
        return plannerOrderBiz.assignUsers(assignIds, plannerId, request);
    }

    /**
     * 保存指定岗位数据
     *
     * @param assignIds
     * @param plannerId
     * @return
     */
    @RequestMapping("/saveAssignPosition")
    @ResponseBody
    public ResultDto saveAssignPosition(String assignIds, String plannerId, HttpServletRequest request) {
        return plannerOrderBiz.assignPositions(assignIds, plannerId, request);
    }

    /**
     * 添加设备跳转页面
     *
     * @return
     */
    @RequestMapping("/addFacilityList")
    public ModelAndView addFacilityList(String plannerId, String serial) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("plannerId", plannerId);
        modelAndView.addObject("serial", serial);
        modelAndView.setViewName("pages/admin/plannerOrder/addFacilityList");

        return modelAndView;
    }

    /**
     * 保存设备数据
     *
     * @param facilityIds
     * @param plannerId
     * @param serial
     * @return
     */
    @RequestMapping("/showFacility")
    @ResponseBody
    public ResultDto showFacility(String facilityIds, String plannerId, String serial, HttpServletRequest request
    ) {
        return facilityMaintainBiz.saveFacility(facilityIds, plannerId, serial, request);
    }


    /**
     * 添加工艺跳转页面
     *
     * @return
     */
    @RequestMapping("/addMaintainList")
    public ModelAndView addMaintainList(String facilityMaintainIds, String plannerId,String catId) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("facilityMaintainIds", facilityMaintainIds);
        modelAndView.addObject("plannerId", plannerId);
        modelAndView.addObject("facilityCatId", catId);
        modelAndView.setViewName("pages/admin/plannerOrder/addMaintainList");
        return modelAndView;
    }

    /**
     * 工艺列表数据
     *
     * @param pageNowParam
     * @param pageSizeParam
     * @param searchCode
     * @param request
     * @return
     */
    @RequestMapping("/maintainJson")
    @ResponseBody
    public JSONObject maintainJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                                   @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                   @RequestParam(value = "searchCode", required = false) String searchCode,
                                   @RequestParam(value = "facilityCatId", required = false) String facilityCatId,

                                   HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.getSqlMap().put("facilityCatId", facilityCatId);
        queryParam.getSqlMap().put("searchCode", searchCode);
        return maintainTechnologyBiz.findJSONList(queryParam);
    }

    /**
     * 保存工艺数据
     *
     * @param facilityMaintainIds
     * @param maintainId
     * @param plannerId
     * @return
     */
    @RequestMapping("/showMaintain")
    @ResponseBody
    public ResultDto showMaintain(String facilityMaintainIds, String maintainId, String plannerId
    ) {
        return facilityMaintainBiz.saveMaintain(facilityMaintainIds, maintainId, plannerId);
    }

    /**
     * 清除工艺
     *
     * @param facilityMaintainIds
     * @return
     */
    @RequestMapping("/removeMaintain")
    @ResponseBody
    public ResultDto removeMaintain(String facilityMaintainIds, String plannerId
    ) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(facilityMaintainIds);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("plannerId", plannerId);
        List<FacilityMaintain> facilityMaintainList = facilityMaintainBiz.findList(queryParam);
        if (jsonArray.size() == facilityMaintainList.size() && StringUtils.isNotBlank(plannerId)) {
            return ResultUtil.error("请至少保留一条工作要求");
        }
        for (Object id : jsonArray) {
            FacilityMaintain facilityMaintain = facilityMaintainBiz.findModel(StringConverters.null2Long(id));
            facilityMaintain.setMaintainId(null);
            facilityMaintain.setMaintainName(null);
            facilityMaintainBiz.addOrUpdate(facilityMaintain);
        }
        return ResultUtil.success();
    }

    /**
     * 删除维保数据
     *
     * @param facilityMaintainIds
     * @return
     */
    @RequestMapping("/deleteFacilityMaintain")
    @ResponseBody
    public ResultDto deleteFacilityMaintain(String facilityMaintainIds, String plannerId
    ) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(facilityMaintainIds);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("plannerId", plannerId);
        queryParam.getSqlMap().put("maintainId", "is not null");
        List<FacilityMaintain> facilityMaintainList = facilityMaintainBiz.findList(queryParam);
        if (jsonArray.size() == facilityMaintainList.size() && StringUtils.isNotBlank(plannerId)) {
            return ResultUtil.error("请至少保留一条完整数据");
        }
        for (Object id : jsonArray) {
            FacilityMaintain facilityMaintain = facilityMaintainBiz.findModel(StringConverters.null2Long(id));
            facilityMaintainBiz.deleteLogic(facilityMaintain);
        }
        return ResultUtil.success();
    }

    /**
     * 开始计划
     *
     * @param ids
     * @param request
     * @return
     */
    @RequestMapping("/startPlanner")
    @ResponseBody
    public ResultDto startPlanner(String ids, HttpServletRequest request) {
        //type, 0:开始计划，1：停止计划，2废弃计划
        return plannerOrderBiz.planner(ids, request, 0, PlannerStatusEnum.START);
    }

    /**
     * 停止计划
     *
     * @param ids
     * @param request
     * @return
     */
    @RequestMapping("/endPlanner")
    @ResponseBody
    public ResultDto endPlanner(String ids, HttpServletRequest request) {
        //type, 0:开始计划，1：停止计划，2废弃计划
        return plannerOrderBiz.planner(ids, request, 1, PlannerStatusEnum.STOP);
    }

    /**
     * 强制生成指定日实施单跳转页面
     *
     * @param plannerId
     * @return
     */
    @RequestMapping("/assignDatePage")
    public ModelAndView assignDatePage(String plannerId) {

        ModelAndView modelAndView = new ModelAndView();
        PlannerOrder plannerOrder = plannerOrderBiz.findModel(StringConverters.null2Long(plannerId));
        modelAndView.addObject("plannerOrder", plannerOrder);
        modelAndView.addObject("end", DateTimeUtils.getLastTimeOfDate(plannerOrder.getEndTime()));
        modelAndView.setViewName("pages/admin/plannerOrder/assignDate");
        return modelAndView;
    }

    /**
     * 保存强制生成指定日实施单
     *
     * @param id
     * @param delay
     * @param delayDate
     * @param request
     * @return
     */
    @RequestMapping("/saveAssignDate")
    @ResponseBody
    public ResultDto saveAssignDate(String id, String delay, String delayDate, HttpServletRequest request) {
        return plannerOrderBiz.saveAssignDate(id, delay, delayDate, request);

    }

    /**
     * 查看生成工单
     *
     * @param id
     * @return
     */
    @RequestMapping("/orderList")
    public ModelAndView orderList(String id) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("plannerId", id);
        modelAndView.setViewName("pages/admin/plannerOrder/orderList");
        return modelAndView;
    }

    /**
     * 工单列表
     *
     * @param pageNowParam
     * @param pageSizeParam
     * @param searchCode
     * @param plannerId
     * @param request
     * @return
     */
    @RequestMapping("/orderJson")
    @ResponseBody
    public JSONObject orderJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                                @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                @RequestParam(value = "searchCode", required = false) String searchCode,
                                @RequestParam(value = "plannerId", required = false) String plannerId,
                                HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("plannerId", plannerId);
        return maintainOrderBiz.findJSONList(queryParam);
    }


    /**
     * 选择部门跳转页
     *
     * @return
     */
    @RequestMapping("/organizationView")
    public ModelAndView organizationView() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/plannerOrder/organizationList");

        return modelAndView;
    }

    @RequestMapping("/getOrganization")
    @ResponseBody
    public JSONObject getOrganization(HttpServletRequest request,
                                      @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                      @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("enterpriseId", SessionKeyUtils.getSessionEnterprise(request).getId() + "");
        return organizationBiz.findJSONList(queryParam);
    }

    /**
     * 导出年度计划
     */
    @RequestMapping("/exportExcel")
    @ResponseBody
    public void exportExcel(String organizationId, HttpServletRequest request, HttpServletResponse response) {
        Organization organization = organizationBiz.findModel(StringConverters.null2Long(organizationId));
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        try {
            //获取模板
            String path = request.getServletContext().getRealPath("")
                    + "/doc/yearPlan.xls";//这个是我的excel模板
            InputStream in = new FileInputStream(new File(path));
            HSSFWorkbook work = new HSSFWorkbook(in);
            // 得到excel的第0张表
            HSSFSheet sheet = work.getSheetAt(0);
            // 这里面的行和列的数法与计算机里的一样，从0开始是第一
            // 设备信息数据，根据设备所属部门进行筛选
            List<Map<String, Object>> list = plannerOrderBiz.getYearPlan(organizationId, enterprise.getId() + "");

            HSSFRow row = sheet.getRow(1);
            HSSFCell cell = row.getCell(0);
            cell.setCellValue(organization.getOrganizationName());//部门
            cell = row.getCell(8);
            cell.setCellValue(list.size());//多少个设备
            cell = row.getCell(12);
            cell.setCellValue(list.size());//多少个数据

            row = sheet.getRow(0);
            cell = row.getCell(10);
            cell.setCellValue(systemUser.getUserName());//导出操作者

            cell = row.getCell(14);
            cell.setCellValue(DateTimeUtils.format(new Date(), "yyyy-MM-dd"));//导出时间

            int i = 4;// 计数器
            int count = 1;//序号

            // 创建每个单元格，添加样式，最后合并
            work.getSheetAt(0).shiftRows(5, 7, list.size() - 1); // 把第三行移动到列表的长度-1的地方  这个地方我是要把模板的第四行放到最后一行
            for (Map map : list) {
                row = sheet.createRow(i);// 得到行
                row.setHeight((short) 700);//行高
                HSSFCellStyle style = work.createCellStyle();//添加边框
                style.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框
                style.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框
                style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
                style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框

                cell = row.createCell(0);//序号
                cell.setCellValue(count);
                cell.setCellStyle(style);

                cell = row.createCell(1);// 得到第0个单元格
                cell.setCellValue(map.get("code").toString());//设备编号
                cell.setCellStyle(style);

                cell = row.createCell(2);
                cell.setCellValue(map.get("name").toString());//设备名称
                cell.setCellStyle(style);

                cell = row.createCell(3);
                cell.setCellValue(map.get("type").toString());//规格
                cell.setCellStyle(style);
                count++;

                for (int j = 4; j < 16; j++) {
                    //设置斜线
                    sheet.setColumnWidth((short) j, (short) 1500);//列宽
                    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                    HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 0, (short) j, i + 1, (short) j, i);
                    HSSFSimpleShape shape1 = patriarch.createSimpleShape(a);
                    shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
                    shape1.setLineStyle(HSSFSimpleShape.LINESTYLE_SOLID);
                    if (j == 15) {
                        HSSFCellStyle style1 = work.createCellStyle();
                        style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
                        row.createCell(15).setCellStyle(style1);//右边框
                    }
                }
                String srcStr = "";//本月安排保养
                String status = "";//实际保养情况
                List<Object> yearPlanVOList = maintainOrderBiz.getYearPlan(map.get("facilityId").toString());//根据设备编号筛选工单
                if (!CollectionUtils.isEmpty(yearPlanVOList)) {
                    srcStr = "√";//发单表示已经安排保养
                    int completeStatus = 0;
                    for (Object o : yearPlanVOList) {
                        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(o);
                        if (!jsonArray.get(3).equals("PASS")) {
                            completeStatus = 1;
                        }
                        if (yearPlanVOList.size() == 1 && (jsonArray.get(3).equals("PASS") || jsonArray.get(3).equals("CANCEL"))) {
                            if (jsonArray.get(4).equals(ApplyTypeEnum.DELAY)) {
                                if (jsonArray.get(6).equals("生产任务紧")) {//延期状态
                                    status = "X1";
                                } else if (jsonArray.get(6).equals("维修任务紧")) {//延期状态
                                    status = "X2";
                                }
                            } else if (jsonArray.get(4).equals(ApplyTypeEnum.CANCEL)) {
                                if (jsonArray.get(6).equals("运行时间未到")) {//取消申请
                                    status = "X";
                                } else if (jsonArray.get(6).equals("其他原因")) {//取消申请
                                    status = "X3";
                                }
                            }
                        }
                        cell = row.createCell(StringConverters.null2Int(jsonArray.get(5)) + 4);
                    }
                    if (completeStatus == 0) {
                        status = "O";
                    }
                    cell.setCellValue(srcStr + "  " + status);


                }
                i++;
            }
/****************************输出流*****************************************/
            String address = DateTimeUtils.format(new Date(), "yyyy-MM-dd");

            String fileName = "年度计划";// URLEncoder.encode("年度计划", "UTF-8");
            fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
            OutputStream os = response.getOutputStream();// 取得输出流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName + "_" + address + ".xls");
            work.write(os);
            os.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件路径错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("文件输入流错误");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
